<template>
 <el-container class="main-contrainer" :class="{'coll': openColl}">
    <el-aside width="">
      <el-scrollbar class="page-component__scroll" wrapClass="pt-menu-scrollbar__view">
        <div class="logo flex-row-ver" @click="openColl=!openColl">
          <img v-if="localhost.indexOf('www.ptgwm.com') > -1" src="assets/img/ptg-logo.png" />
          <img v-else src="assets/img/wg-logo.png" />
        </div>
        <div class="user-cont" v-if="!openColl">{{loginMsg.user}}</div>
        <div class="set">
          <el-dropdown class="column-btn" placement="right">
            <div class="el-dropdown-link">
              <span v-if="!openColl">
                设置<icon-svg icon="xiangyou" />
              </span>
              <icon-svg style="width: 1.5em;height:1.5em" v-else icon="xitong" />
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item class="flex-row-row">
                <el-button class="el-text-warning" type='text'
                  style="width: 100%;text-align: center;"
                  @click="dialogTableVisible = true">修改密码</el-button>
              </el-dropdown-item>
              <el-dropdown-item class="flex-row-row">
                <el-button class="el-text-info" type='text'
                  style="width: 100%;text-align: center;" 
                  @click="outLogin()">退出登录</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <pt-menu :menuList="menuList" :openColl="openColl" :scrollTop="scrollTop" :wrapHeight="wrapHeight" />
      </el-scrollbar>
    </el-aside>
    <el-container class="main-contrainer">
      <el-header class="header" height="">
        <div class="right-header flex-row">
          <div class="placeul flex-row">
            <span class="title">{{$route.meta.menu}}</span>
            <i class="el-icon-arrow-right"></i>
            <span class="title">{{$route.meta.children}}</span>
          </div>
          <div class="right-menu">
            <div class="seachye flex-row">
              <router-link v-if="$store.state.type === 2 || $store.state.type === 3" tag="div"
                          :to="{path:'/main/member/info'}" class='yuer-wrap flex-row'
                          :class="{ 'cur': loginMsg.remainer >= 1000 }">
                <span class="icon-wrap flex-row-ver"><i class="el-icon1-erp-iconmoney"></i></span>
                账户余额：{{loginMsg.remainer}}
                <span style="padding:0 5px;">|</span><span>查看</span>
              </router-link>
              <span class="nut" v-if="$store.state.type === 2 || $store.state.type === 3">|</span>
              <router-link v-if="$store.state.type === 1 || $store.state.type === 2 || $store.state.type === 3" tag='div'
                           class='in-form head-yuen-youxiang'  :to="{path:'/main/inform/index'}">
                <el-badge :value="sumList.total || ''" :max="99" class="num-int">
                  <span class='flex-row'><i class='el-icon1-erp-youxiang' style='font-size: 25px;'></i> </span>
                </el-badge>
              </router-link>
              <router-link v-if="$store.state.type === 2 || $store.state.type === 3"
                           tag='div' class='in-form head-yuen-youxiang' :to="{path:'/main/busnt/joinList'}">
                <el-badge :value="sumList.businessTotal || ''" :max="99" class="num-text">
                  <span class='flex-row'>商家入驻 </span>
                </el-badge>
              </router-link>
              <router-link v-if="$store.state.type === 2 || $store.state.type === 3"
                           tag='div' class='in-form head-yuen-youxiang' :to="{path:'/main/knight/joinList'}">
                <el-badge :value="sumList.shopperTotal ||''" :max="99" class="num-text">
                  <span class='flex-row'>骑手申请</span>
                </el-badge>
              </router-link>
            </div>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-scrollbar class="main-wrap__scroll">
          <div class="main-wrap">
            <keep-alive include="busntList">
              <router-view  />
            </keep-alive>
          </div>
        </el-scrollbar>
      </el-main>
    </el-container>
    <el-dialog title="修改密码" v-dialogDrag :visible.sync="dialogTableVisible" width="380px" height="500px">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="85px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="ruleForm.oldPassword" type="password" style="width:220px;"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword1">
          <el-input v-model="ruleForm.newPassword1" type="password" style="width:220px;"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="newPassword2">
          <el-input v-model="ruleForm.newPassword2" type="password" style="width:220px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
          <el-button @click="resetForm('ruleForm')" style="margin-left: 50px;">重填</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-container>
</template>

<script>
import ptMenu from '@/components/pt-menu'
import imd5 from '@/utils/md5.js'
import { menuListApi, agentList, selectAgent, selectAllAgent, agentUnreadNum, password } from "@/api/com";
export default {
  provide() {
    return {
      loadAll: this.loadAll,
      upDataAgentArea: this.getselectAgent,
      upDateMoney: this.upDateMoney, // 充值本地更新money
      updateSumTotal: this.getNoticeNum // 充值本地更新money
    }
  },
  components: { ptMenu },
  data() {
    var validateOldPass = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入原始密码'))
      } else {
        callback()
      }
    };
    var validatePass1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.newPassword2 !== '') {
          this.$refs.ruleForm.validateField('newPassword2')
        }
        callback()
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.newPassword1) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback();
      }
    };
    return {
      localhost: window.location.href,
      loginMsg: {}, // 用户信息
      openColl: false, // z展开菜单列表
      menuList: [],
      wrapHeight: 0,
      scrollTop: 0,
      dialogTableVisible: false,
      ruleForm: {
        oldPassword: '',
        newPassword1: '',
        newPassword2: ''
      },
      sumList: {}, // 数量统计
      rules: {
        oldPassword: [{validator: validateOldPass, trigger: 'blur'}],
        newPassword1: [
          {validator: validatePass1, trigger: 'blur'},
          {min: 6, max: 18, message: "密码6到18个字符", trigger: 'blur'}
        ],
        newPassword2: [
          {validator: validatePass2, trigger: 'blur'},
          {min: 6, max: 18, message: "密码6到18个字符", trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    upDateMoney(money) { // 更新金额
      this.loginMsg.remainer = money
      sessionStorage.setItem('loginMsg', JSON.stringify(this.loginMsg))
    },
    submitForm(formName) { //修改密码
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = { password: imd5.md5(this.ruleForm.oldPassword), newPassword: imd5.md5(this.ruleForm.newPassword2)  }
          password(params).then(res => {
            if (res.success) {
              this.$alert( '密码修改成功,请用新密码重新登录!', '修改密码提示!', {
                  confirmButtonText: '确定',
                  closeOnPressEscape: true,
                  callback: action => {
                    sessionStorage.removeItem("loginMsg")
                    this.$store.commit('set_LoginInfo', {})
                    this.$router.push({
                      path: '/main/login',
                      query: { redirect: this.$route.path }
                    })
                  }
                }
              )
            }
          })
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getNoticeNum() { // 头部通知数量统计
      agentUnreadNum().then(res => {
        if (res.success) {
          this.sumList = res.data
        }
      })
    },
    outLogin() { // 退出登录
      this.$confirm("是否确认退出登录?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(() => {
        this.$message({ type: "success", message: "成功退出登录!" })
        sessionStorage.removeItem("loginMsg")
        this.$store.commit('set_LoginInfo', {})
        this.$router.push({ path: '/main/login' })
      }).catch(() => {
        this.$message({ type: "info", message: "已取消退出登录" })
      })
    },
    loadAll(callback) { // 获取区域列表-过滤总区域
      agentList().then(res => {
        if (res.success) {
          this.$store.commit('Set_agentList', res.data)
          this.$store.commit('SET_LoginType', this.loginMsg.type)
          const t = this.loginMsg.type
          const showAgent = t === 1 || t === 3 // 账号权限
          this.$store.commit('SET_loginShowAgent', showAgent) // 是否显示下拉代理商组件
          if (callback) callback()
        }
      })
    },
    getselectAgent() {  // 获取区域列表-过滤了子区域
      selectAgent().then(res => {
        if (res.success) {
          this.$store.commit('Set_agentListArea', res.data)
        }
      })
    },
    getSelectAllAgent() { // 获取所有的代理商
      selectAllAgent().then(res => {
        if (res.success) {
          this.$store.commit('Set_agentListAll', res.data)
        }
      })
    },
    getMenuList() { // 菜单
      menuListApi().then(res => {
        if (res.success) {
          this.menuList = res.data.menuList
        }
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
     const scrollDiv = document.querySelector('.pt-menu-scrollbar__view')
      this.wrapHeight = scrollDiv.offsetHeight
      window.onresize = () => {
        return (() => {
          this.wrapHeight = scrollDiv.offsetHeight
        })()
      }
      scrollDiv.addEventListener('scroll', () => {
        this.scrollTop = scrollDiv.scrollTop
      })
      window.addEventListener('resize', () => { // 全局resize事件
        const screenRice = {
          width: document.documentElement.clientWidth,
          height: document.documentElement.clientHeight
        }
        this.$store.commit('Set_screenRice', screenRice)
      })
    })
  },
  created() {
    const loginMsg = sessionStorage.getItem('loginMsg') || '{}'
    this.loginMsg = JSON.parse(loginMsg)
    this.$store.commit('set_LoginInfo', this.loginMsg)
    this.getMenuList()
    this.getNoticeNum()
    this.loadAll()
    this.getselectAgent()
    this.getSelectAllAgent()
  }
};
</script>

<style lang="scss" scoped >
  ::-webkit-scrollbar {
    display: none;
  }
  @import "./css/main.scss";
</style>
